package com.cd.schedule.api.impl;

import com.cd.schedule.api.CalenderService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cd.schedule.jpa.domain.ScheduleEntity;
import com.cd.schedule.jpa.repo.ScheduleEntityRepo;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CalenderServiceImpl implements CalenderService {

    @Autowired
    private ScheduleEntityRepo scheduleEntityRepo;

    private static final Logger logger = org.slf4j.LoggerFactory.getLogger(CalenderServiceImpl.class);

    @Override
    public List<ScheduleEntity> findSchedulesByUserId(Long userId) {
        return scheduleEntityRepo.findByUserId(userId);
    }

    @Override
    public String removeSchedulesByUserId(Long scheduleId) {
        scheduleEntityRepo.deleteByScheduleId(scheduleId);
        return "删除成功";
    }

    @Override
    public ScheduleEntity modifySchedules(ScheduleEntity schedule) {
        logger.info(schedule.toString());
        validateScheduleConflict(schedule);
        return scheduleEntityRepo.save(schedule);
    }

    private void validateScheduleConflict(ScheduleEntity newSchedule) {
        // 查询该用户当天所有日程
        List<ScheduleEntity> existingSchedules = scheduleEntityRepo.findByUserIdAndDate(
                newSchedule.getUserId(),
                newSchedule.getDate()
        );

        // 排除自身（如果是修改操作）
        existingSchedules = existingSchedules.stream()
                .filter(s -> !s.getScheduleId().equals(newSchedule.getScheduleId()))
                .collect(Collectors.toList());

        // 检查时间冲突
        for (ScheduleEntity existing : existingSchedules) {
            if (isTimeOverlap(
                    newSchedule.getStartHour(),
                    newSchedule.getEndHour(),
                    existing.getStartHour(),
                    existing.getEndHour()
            )) {
                throw new RuntimeException("该时间段已有其他日程安排，请选择其他时间");
            }
        }
    }

    // 判断两个时间段是否有重叠
    private boolean isTimeOverlap(String start1, String end1, String start2, String end2) {
        // 将时间转换为分钟数便于比较
        int newStart = convertTimeToMinutes(start1);
        int newEnd = convertTimeToMinutes(end1);
        int existStart = convertTimeToMinutes(start2);
        int existEnd = convertTimeToMinutes(end2);

        return newStart < existEnd && newEnd > existStart;
    }

    // 将HH:mm格式时间转换为分钟数
    private int convertTimeToMinutes(String time) {
        String[] parts = time.split(":");
        return Integer.parseInt(parts[0]) * 60 + Integer.parseInt(parts[1]);
    }
}
